//
//  ViewController.m
//  CoreDataContact
//
//  Created by 王婷 on 15/11/21.
//  Copyright © 2015年 王婷. All rights reserved.
//

#import "ViewController.h"
#import "WTPersonTableViewCell.h"
#import "Entity.h"
#import "WTCoreDataManager.h"
#import "WTDetailViewController.h"

@interface ViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchResultsUpdating>

@property (nonatomic, strong)WTCoreDataManager *manager;
@property (nonatomic, strong)NSMutableArray *mArr;
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property(strong, nonatomic)UISearchController *searchController;

@property(nonatomic, retain)NSMutableArray *displayArr;


@end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated {
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.manager = [WTCoreDataManager shareDefaults];
    NSLog(@"url == %@", [self.manager applicationDocumentsDirectory]);
    [self.manager applicationDocumentsDirectory];
    
    self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
    // 将搜索结果更新器设为self
    self.searchController.searchResultsUpdater = self;
    self.searchController.dimsBackgroundDuringPresentation = false;
    [self.searchController.searchBar sizeToFit];
    self.searchController.searchBar.backgroundColor = [UIColor grayColor];
    self.tableView.tableHeaderView = self.searchController.searchBar;
    
    
    [self createData];
    [self.tableView reloadData];
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController {
    // 获取查询数据的请求, 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];// 实体
    // 生成约束 谓词(只有两种答案)
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"],  searchController.searchBar.text];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name contains %@ || sex contains %@ || number contains %@", searchController.searchBar.text, searchController.searchBar.text, searchController.searchBar.text];
    
    request.predicate = predicate;// 给查询请求添加约束(谓词)
    // 通过某个key 给数组排序
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error;
    
    self.displayArr = [NSMutableArray arrayWithArray:[self.manager.managedObjectContext executeFetchRequest:request error:&error]];
    
    [self.tableView reloadData];
}

- (void)createData {
    // 获取查询数据的请求, 相当于数据库的查询语句
    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
    // 生成约束 谓词
    NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"flag", @"%@"], @"1"];
    request.predicate = predicate;
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"flag" ascending:YES];
    [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    NSError *error;
    
    self.mArr = [NSMutableArray arrayWithArray:[self.manager.managedObjectContext executeFetchRequest:request error:&error]];
    NSLog(@"%ld", self.mArr.count);
//    self.mArr = [NSMutableArray arrayWithObjects:[self.manager.managedObjectContext executeFetchRequest:request error:&error], nil] ;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (!self.searchController.active) {
        return self.mArr.count;
    } else {
        return self.displayArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *reuse = @"reuse";
    WTPersonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[WTPersonTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuse];
    }
    if (!self.searchController.active) {
        Entity *per = self.mArr[indexPath.row];
        cell.nameLabel.text = per.name;
        cell.sexLabel.text = per.sex;
        cell.numberLabel.text = per.number.stringValue;
        return cell;
    } else {
        Entity *per = self.displayArr[indexPath.row];
        cell.nameLabel.text = per.name;
        cell.sexLabel.text = per.sex;
        cell.numberLabel.text = per.number.stringValue;
        return cell;
    }
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    return UITableViewCellEditingStyleDelete;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // 获取查询数据的请求, 相当于数据库的查询语句
        NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];// 实体
        // 生成约束 谓词(只有两种答案)
        Entity *per = self.mArr[indexPath.row];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"name", @"%@"], per.name];
        request.predicate = predicate; // 给查询请求添加约束(谓词)
        // 通过某个key 给数组排序
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];
        [request setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
        
        NSError *error;
        NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
        
        for (Entity *per in array) {
            [self.manager.managedObjectContext deleteObject:per];
        }
        
        [self.manager saveContext];
        
        
        [self.mArr removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft];
    }
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    WTDetailViewController *detailVC = segue.destinationViewController;
    WTPersonTableViewCell *cell = (WTPersonTableViewCell *)sender;
    NSIndexPath *index = [self.tableView indexPathForCell:cell];
    Entity *per = self.mArr[index.row];
    detailVC.per = per;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
